<template>
  <div class="modal">
    <div class="head_navigat">
      <div class="title">成就管理</div>
      <div class="button-container">
        <div>
          <button @click="onAddItem">添加</button>
        </div>
        <!-- <div class="saveButton">
          <button @click="save">保存到剧本</button>
        </div> -->

      </div>
    </div>
    <div class="content">
      <el-table :data="tableData">
        <el-table-column fixed prop="pictureUrl" label="图片" width="218.18">
          <template v-slot="{ row }">
            <el-image
              style="height: 100px; width: 100px"
              :src="row.pictureUrl"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="成就名称" width="407.15">
          <template v-slot="{ row }">
            <el-input
              v-model="row.name"
              style="width: 360px; height: 50px"
              @input="() => handleInput({ row })"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodspath" label="成就路径" width="415.84">
          <template v-slot="{ row }">
            <el-upload
              v-model:file-list="row.goodspath"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="file => handleExceed({ file, row })"
              :auto-upload="false"
              class="elUploadContainer"
              :limit="1"
            >
              <div class="el-upload-list" />
              <div class="upload-button-container">
                <el-button type="primary">请上传文件</el-button>
              </div>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="130">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.row.id)"
            >
              <img src="/svg/trashCan.svg" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 成就管理的内容 -->
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { UploadProps } from "element-plus";
import {
  delAchievement,
  getAchievementById,
  addAchievement,
  updateAchievement
} from "@/api/achievement";
import { useRoute, useRouter } from "vue-router";
import { message } from "@/utils/message";
import { uploadFileApi } from "@/api/common";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();

const now = new Date();
const scriptId = ref(0);

const tableData = ref([]);

const initAchievement = ref({
  scriptId: 0,
  name: "默认图片",
  // 这是一张默认图片的地址
  pictureUrl:
    "https://www.supboxcity.com/lost/city/login/showImage/d3154956-cce5-4d5c-a67d-8b3124ebf381.jpg",
  image:
    "https://www.supboxcity.com/lost/city/login/showImage/d3154956-cce5-4d5c-a67d-8b3124ebf381.jpg",
  goodspath: []
});

const handleInput = ({ row }) => {
  row.scriptId = scriptId.value;
  updateAchievement(row).then(res => {
    if (res.code === "0000") {

    } else {
      message(res.message, {
        type: "error"
      });
    }
  });
};

const deleteRow = (id: number) => {
  console.log(id);
  delAchievement(id).then(res => {
    if (res.code === "0000") {
      tableData.value.splice(id, 1);

    } else {
      message(res.message, {
        type: "error"
      });
    }
    refreshAchievement(scriptId.value);
  });
};
const onAddItem = () => {
  addAchievement(initAchievement.value).then(res => {
    if (res.code === "0000") {
      tableData.value.unshift(initAchievement);
    } else {
      ElMessage.error(res.message);
    }
    refreshAchievement(scriptId.value);
  });
};
const refreshAchievement = (scriptId: number) => {
  tableData.value = [];
  getAchievementById(scriptId).then(res => {
    const goodsList = res.data.list;
    for (let i = 0; i < goodsList.length; i++) {
      tableData.value.push({
        id: goodsList[i].id,
        name: goodsList[i].name,
        pictureUrl: goodsList[i].image,
        goodspath: [
          {
            name:
              goodsList[i].name +
              "." +
              goodsList[i].image?.split(".").pop().toLowerCase(),
            url: goodsList[i].image
          }
        ]
      });
    }
  });
};
onMounted(() => {
  scriptId.value = Number(route.query.scriptId);
  initAchievement.value.scriptId = scriptId.value;
  if (!scriptId.value) {
    router.push("/error/404");
  } else {
    refreshAchievement(scriptId.value);
  }
});
const save = () => {
  // alert("保存成功")
  //   保存到pinia 里面
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = file => {
  console.log(file);
};
const handleBeforeUpload = row => {
  console.log("上传前的检查");
  console.log(row.id);
};
const handleExceed = ({ file, row }) => {
  const formData = new FormData();
  formData.append("file", file.raw);
  // 验证 FormData 的内容
  uploadFileApi(formData)
    .then(res => {
      if (res.code === "0000") {
        // 将上传的文件路径保存到 formInline.image 属性中
        row.goodspath[0] = {
          name: file.name,
          url: res.data
        };
        row.pictureUrl = res.data;
        row.image = res.data;
        row.scriptId = scriptId.value;
        //   更新接口
        updateAchievement(row).then(res => {
          if (res.code === "0000") {

          } else {
            ElMessage.error("更新失败");
          }
        });
      }
      console.log(row);
    })
    .catch(err => {
      console.log("上传附件失败::::" + err);
    });
};
</script>
<style>
.elUploadContainer {
  border: #0bdcb7 0px solid;
  background-color: #232323;
  border-radius: 10px;
  width: 360px;
  height: 50px;
  justify-content: space-between;

  .el-upload-list {
    padding-top: 30px;
    color: white;
  }

  .upload-button-container {
    padding-left: 250px;
    padding-top: 7px;
  }
}

.el-upload-list__item {
  width: 200px;
}

.el-table {
  height: 627.49px;
  background-color: #383838;
}

.el-table__header {
  width: 1170px !important;
  background-color: #383838 !important;
}
</style>

<style scoped>
.modal {
  /* 样式 */
  width: 1170px;
  height: 707.39px;

  .head_navigat {
    height: 80px;
    width: 1170px;
    background-color: #525252;
    display: flex;
    padding-top: 24px;
    padding-bottom: 25px;

    .title {
      font-size: 22px;
      font-weight: 50;
      padding-left: 540.28px;
    }

    .button-container {
      padding-left: 200px;
      display: flex;

      button {
        width: 100px;
        height: 40px;
        background-color: #232323;
        font-size: 16.18px;
        font-weight: 500;
        line-height: 24.27px;
        border-radius: 7px;
      }

      .saveButton {
        padding-left: 20px;

        button {
          background-color: #fc8b1a;
        }

        width: 100px;
        height: 40px;
        font-size: 16.18px;
        font-weight: 500;
        line-height: 24.27px;
        border-radius: 7px;
        color: black;
      }

      .exitIcon {
        padding-left: 55px;
        padding-top: 3px;
      }
    }
  }

  .content {
    height: 627.04px;
    background-color: #383838;
    display: flex;
    overflow: auto;
  }
}
</style>
